package com.example.design.adapter;

import com.alibaba.fastjson.JSONObject;
import com.example.design.pojo.UserInfo;
import com.example.design.sercive.UserService;
import com.example.design.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class Login3rdAdapter extends UserService implements Login3rdTarget{

    @Value("${gitee.state}")
    private String giteeState;

    @Value("${gitee.token.url}")
    private String giteeTokenUrl;

    @Value("${gitee.user.url}")
    private String giteeUserUrl;

    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;



    @Override
    public String loginByGitee(String code, String state) {
        //进行state判断，state值是前端和后端约好的，前端将state传给gitee,gitee平台传回state给回调接口
        if (!giteeState.equals(state)){
            throw new UnsupportedOperationException("state值不匹配");
        }
        //获取token
        String tokenUrl = giteeTokenUrl.concat(code);
        JSONObject jsonObject = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
        String token = String.valueOf(jsonObject);
        //请求用户信息并携带token
        String userUrl = giteeUserUrl.concat(token);
        JSONObject userInfoResponse = HttpClientUtils.execute(userUrl, HttpMethod.GET);
        //获取用户信息，userName添加前缀GITEE@，密码保持与UserName一致
        String userName = giteeUserPrefix.concat(String.valueOf(userInfoResponse.get("name")));

        String password = userName;

        return autoRegister3rdLogin(userName,password);
    }

    public String autoRegister3rdLogin(String userName,String password){
        //如果第三方账号已经注册过，直接登录
        if (super.isExist(userName)){
            return super.login(userName,password);
        }
        //组装用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userInfo.setCreateDate(new Date());
        //如果第三方账号是第一次登录，先进行自动登录
        super.register(userInfo);
        //自动注册成功后，登录
        return super.login(userName,password);

    }

    @Override
    public String loginByWechat(String... params) {
        return null;
    }

    @Override
    public String loginByQQ(String... params) {
        return null;
    }
}
